<template>
  <div class="stepschild1_container">
    <div class="from_box">
      <!-- 32.4写 step1 的结构 -->
      <el-form style="width: 600px" label-width="120px" :model="form" :rules="rules" ref="ruleForm">
        <!-- 下拉 -->
        <!-- 32.5商品分类下拉选项的数据，去到接口文档发送请求 pms 文件夹里面的 api.ts -->
        <el-form-item label="商品分类：" prop="productCategoryId">
          <!-- Cascader 级联选择器 --- 基础用法 -->
          <!-- <el-select placeholder="请选择" v-model="form.productCategory">
            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select> -->
          <el-cascader placeholder="请选择" v-model="form.productCategoryId" @change="handleChange"
            :options="categoryOptions" />
        </el-form-item>
        <!-- 输入框 -->
        <el-form-item label="商品名称：" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="副标题：" prop="subTitle">
          <el-input v-model="form.subTitle" />
        </el-form-item>
        <el-form-item label="商品品牌：" prop="brandId">
          <!-- 32.10商品品牌下拉选项，去到 pms 文件夹里面的 api.ts  -->
          <el-select placeholder="请选择品牌" v-model="form.brandId" @change="handleChange2">
            <el-option v-for="item in brandOptions" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 文本域 -->
        <el-form-item label="商品介绍：" prop="description">
          <el-input autocomplete="off" placeholder="请输入内容" type="textarea" v-model="form.description" />
        </el-form-item>
        <el-form-item label="商品货号：" prop="productSn">
          <el-input v-model="form.productSn" />
        </el-form-item>
        <el-form-item label="商品售价：" prop="price">
          <el-input v-model="form.price" />
        </el-form-item>
        <el-form-item label="市场价：" prop="originalPrice">
          <el-input v-model="form.originalPrice" />
        </el-form-item>
        <el-form-item label="商品库存：" prop="stock">
          <el-input v-model="form.stock" />
        </el-form-item>
        <el-form-item label="计量单位：" prop="unit">
          <el-input v-model="form.unit" />
        </el-form-item>
        <el-form-item label="商品重量：" style="width: 360px;" prop="weight">
          <el-input v-model="form.weight" style="width:300px">
          </el-input>
          <span style="position: absolute;right: -20px;">克</span>
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input v-model="form.sort" />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
// @ts-ignore
import { ApiGetBrandCategory, ApiGetProductCategoryWithcChikdren } from '@/http/pms/api';
import { reactive, ref } from 'vue';
// @ts-ignore
import type { FormInstance, FormRules } from 'element-plus';

const forminit = {
  productCategoryName: "", //商品分类名字 
  productCategoryId: '',// 商品分类
  name: '',// 商品名称
  subTitle: '',// 副标题
  brandName: '',//品牌名称
  brandId: '',// 商品品牌
  description: '',// 商品介绍
  productSn: '',// 商品货号
  price: 0,// 商品售价
  originalPrice: 0,// 市场价
  stock: 0,// 商品库存
  unit: '',// 计量单位
  weight: 0,// 商品重量
  sort: 0,// 排序
  // 以下是没有用
  deleteStatus: 0,//是否已删除
  feightTemplateId: 0,//运费模板 ID 
  promotionPerLimit: 0,//促销限购数量
  sale: 0,//商品销量
  verifyStatus: 0,//审核状态 
  albumPics: "",//商品图片，以 "," 分割
  skuStockList: [],//商品的sku库存信息
  //商品会员价格设置
  memberPriceList: [
    {
      memberLevelId: 1,
      memberLevelName: "黄金会员",
      //会员价格
      // memberPrice: 0,
      // productId: 0,
    },
    {
      memberLevelId: 2,
      memberLevelName: "白金会员",
      //会员价格
      // memberPrice: 0,
      // productId: 0,
    },
    {
      memberLevelId: 3,
      memberLevelName: "钻石会员",
      //会员价格
      // memberPrice: 0,
      // productId: 0,
    },
  ],
  //商品满减价格设置
  productFullReductionList: [
    {
      fullPrice: 0,
      // id: 0,
      // productId: 0,
      reducePrice: 0,
    },
  ],
  //商品阶梯价格设置
  productLadderList: [
    {
      //满足的商品数量
      count: 0,
      //折扣
      discount: 0,
      // id: 0,
      //折后价格
      price: 0,
      // productId: 0,
    },
  ],
  detailHtml: "",
  detailMobileHtml: "",
  flashPromotionCount: 0,
  flashPromotionId: 0,
  flashPromotionPrice: 0,
  flashPromotionSort: 0,
}

// 把form表单的数据做成响应式
const form = reactive({ ...forminit })

interface selectOptions {
  id: number,
  name: string,
  children: []
}
interface selectOptions2 {
  value: number,
  label: string,
  children: {
    value: number,
    label: string
  }
}
// 32.8新建一个存 商品分类 --- 选项内容
const categoryOptions = ref<selectOptions2[]>([])

// 32.14创建一个存 商品品牌 --- 选择内容
const brandOptions = ref<selectOptions[]>([])

// rules 校验方法
const rules = ref<any>({
  productCategoryId: [
    {
      required: true,
      trigger: 'blur',
      message: '请选择商品分类'
    }],
  name: [
    {
      required: true,
      trigger: 'blur',
      message: '请选择商品名称'
    },
    { min: 2, max: 12, message: "长度在 2 到 12 个字符", trigger: "blur" }
  ],
  subTitle: [{
    required: true,
    trigger: 'blur',
    message: '请选择商品副标题'
  }],
  brandId: [{
    required: true,
    trigger: 'blur',
    message: '请选择商品品牌'
  }]
})

// 32.7发送请求商品分类下拉的接口数据
ApiGetProductCategoryWithcChikdren().then(res => {
  // console.log(res);
  if (res.code === 200) {
    // 32.9将数据里面的 name 跟 id 拿出来
    categoryOptions.value = res.data.map((item: any) => {
      if (item.children.length === 0) {
        return {
          value: item.id,
          label: item.name,
          // 禁用
          disabled: true
        }
      } else {
        return {
          value: item.id,
          label: item.name,
          children: item.children.map((child: any) => {
            return {
              value: child.id,
              label: child.name,
              children: [],
            }
          }),
        }
      }
    })
    // 查看是否赋值成功
    // console.log(categoryOptions.value);
  }
})

// 32.12发送请求获取商品品牌的数据
ApiGetBrandCategory().then(res => {
  // 32.13查看请求回来的数据
  // console.log(res);
  if (res.code === 200) {
    // 32.15将数据里面的 name 跟 id 拿出来
    brandOptions.value = res.data.map((item: any) => ({
      id: item.id,
      name: item.name
    }))
  }
  // 查看是否赋值成功
  // console.log(brandOptions.value);
})

// 点击联级选择器，可以拿到对应的数据
const handleChange = (value: any) => {
  // console.log(value)
  form.productCategoryId = value[1]
  // console.log(form.productCategoryId);//97
  // console.log(categoryOptions.value);
  let resultItem: any = {}
  const filter = (list: any, id: string) => {
    list.forEach((item: any) => {
      if (item.children && item.children.length > 0) {
        filter(item.children, id)
      } else {
        if (item.value == id) {
          resultItem = item
        }
      }
    })
    return resultItem
  }
  const result = filter(categoryOptions.value, form.productCategoryId)
  // console.log(result)
  // console.log(result.label);
  form.productCategoryName = result.label
}

// 商品品牌点击选择事件
const handleChange2 = (value: any) => {
  // console.log(value);
  // console.log(brandOptions.value);
  let resultItem: any = {}
  const filter = (list: any, id: string) => {
    list.forEach((item: any) => {
      if (item.id == id) {
        resultItem = item
      }
    })
    return resultItem
  }
  const result = filter(brandOptions.value, value)
  // console.log(result.name);
  form.brandName = result.name

}

// 先获取到ref
const ruleForm = ref<any>(null)
// 校验方法
const test = async (callback: any) => {
  await ruleForm.value.validate((valid: any) => {
    // console.log(valid)
    if (valid) {
      callback(form)
    } else {
      return false
    }
  })
}

// 将子组件表单数据暴露
defineExpose({
  form,
  test,
  ruleForm
})

</script>

<style lang="less" scoped>
.stepschild1_container {
  display: flex;
  flex-direction: column;

  .from_box {
    margin-top: 60px;
  }
}
</style>